<template>
	<view>
		<view class="dataArea">
			<view class="title">
				<view class="title_line"></view>
				<text class="title_text">用户概况</text>
			</view>
			<view class="data">
				<view class="dataItem">
					<view><u-text :text="totalGrowCount" bold size="48rpx" color="#3d3d3d" /></view>
					<view><u-text text="用户总数" size="24rpx" color="#777" /></view>
				</view>
				<view>
					<u-line direction="col" length="50rpx"></u-line>
				</view>
				<view class="dataItem">
					<view><u-text :text="todayGrowCount" bold size="48rpx" color="#3d3d3d" /></view>
					<view><u-text text="今日增长" size="24rpx" color="#777"
							suffixIcon="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/24/e905b8ea4b1e4c9ca996926075690ac8.png"
							iconStyle="width:24rpx;height:24rpx" /></view>
				</view>
			</view>
		</view>
		<view class="components">
			<view class="head">
				<view class="title">
					<view class="title_line"></view>
					<text class="title_text">客户增加数量</text>
				</view>
				<u-button :text="currentFilterDate.text" :customStyle="buttonCustomStyle" color="#DBE7FF" size="mini"
					@click="openPicker" />
			</view>
			<view class="line">
				<l-echart ref="chartLine" />
			</view>
		</view>

		<view class="components">
			<view class="head">
				<view class="title">
					<view class="title_line"></view>
					<text class="title_text">用户增长来源</text>
				</view>
				<u-button :text="currentFilterDate2.text" :customStyle="buttonCustomStyle" color="#DBE7FF" size="mini"
					@click="openPicker2" />
			</view>
			<view class="pie">
				<l-echart ref="chartPie" />
			</view>
		</view>
		<u-picker :show="showPicker" :columns="[filterList]" :defaultIndex="defaultIndex" keyName="text"
			closeOnClickOverlay @close="closePicker" @cancel="closePicker" @confirm="confirm" />

		<u-picker :show="showPicker2" :columns="[filterList]" :defaultIndex="defaultIndex" keyName="text"
			closeOnClickOverlay @close="closePicker2" @cancel="closePicker2" @confirm="confirm2" />
	</view>
</template>

<script>
	import * as echarts from "../components/lime-echart/static/echarts.min.js";
	import lEchart from "../components/lime-echart/components/l-echart/l-echart.vue"
	import {
		getLineDataList,
		getPieDataList,
		getUserData
	} from '@/api/operate.js'

	export default {
		components: {
			lEchart
		},
		data() {
			return {
				showPicker: false,
				showPicker2: false,
				defaultIndex: [0],
				totalGrowCount: 0,
				todayGrowCount: 0,
				pieEnum: {
					0: '扫码业务员资讯',
					1: '扫码业务视频',
					2: '扫码业务商品',
					3: '扫码业务员',
					4: '激活权益卡',
					5: '签到',
					6: '领取',
					9: '其他',
				},
				buttonCustomStyle: {
					width: "138rpx",
					height: "44rpx",
					color: "#588BF3",
					fontSize: "20rpx",
					margin: "0"

				},
				currentFilterDate: {
					text: '最近一年',
					value: 12,
					type: 'months'
				},
				currentFilterDate2: {
					text: '最近一年',
					value: 12,
					type: 'months'
				},
				filterList: [{
					text: '最近一年',
					value: 12,
					type: 'months'
				}, {
					text: '最近90天',
					value: 3,
					type: 'months'
				}, {
					text: '最近30天',
					value: 30,
					type: 'days'
				}, {
					text: '最近7天',
					value: 7,
					type: 'days'
				}],
				defaultPieData: [{
						value: 0,
						name: "扫码业务员资讯",
						nameType: 0
					},
					{
						value: 0,
						name: "扫码业务视频",
						nameType: 1
					},
					{
						value: 0,
						name: "扫码业务商品",
						nameType: 2
					},
					{
						value: 0,
						name: "扫码业务员",
						nameType: 3
					},
					{
						value: 0,
						name: "激活权益卡",
						nameType: 4
					},
					{
						value: 0,
						name: "签到",
						nameType: 5
					},
					{
						value: 0,
						name: "领取",
						nameType: 6
					},
					{
						value: 0,
						name: "其他",
						nameType: 9
					}
				],
				optionPie: {
					tooltip: {
						trigger: "item",
						textStyle: {
							fontSize: uni.upx2px(24),
						},
					},
					legend: {
						orient: "vertical",
						top: uni.upx2px(28),
						right: uni.upx2px(10),
						width: uni.upx2px(280),
						textStyle: {
							fontSize: uni.upx2px(16),
						},
						itemWidth: uni.upx2px(20),
						itemHeight: uni.upx2px(14),
						itemGap: uni.upx2px(36),
					},
					series: [{
						type: "pie",
						left: uni.upx2px(20),
						top: uni.upx2px(23),
						width: uni.upx2px(250),
						height: uni.upx2px(250),
						radius: [0, "100%"],
						selectedMode: true,
						selectedOffset: uni.upx2px(10),
						data: [],
						label: {
							position: "inside",
							color: "#FFF",
							fontSize: uni.upx2px(20),
							formatter: "{d}%",
						},
					}, ],
				},
				optionLine: {
					title: {
						text: "单位/人", // 使用富文本格式
						textAlign: "left",
						top: "6%",
						textStyle: {
							width: uni.upx2px(644),
							color: "#86909C",
							fontSize: uni.upx2px(20),
						},
					},
					tooltip: {
						show: true,
						trigger: "axis",
						position: "top",
					},
					formatter: "{b}：{c}人",
					xAxis: {
						data: [],
						type: "category",
						boundaryGap: false,
						axisTick: {
							show: false,
						},
						axisLabel: {
							fontSize: uni.upx2px(16),
							color: "#86909C",
							rotate: 40,
						},
					},
					yAxis: {
						type: "value",
						axisLabel: {
							fontSize: uni.upx2px(20),
							color: "#86909C",
						},
						min: 0,
						interval: 30,
						splitNumber: 5,
						splitLine: {
							show: true,
							lineStyle: {
								type: "dashed",
								color: "#E5E6EB",
							},
						},
					},
					grid: {
						top: "24%",
						left: "12%",
						right: "4%",
						bottom: "20%",
					},
					series: [{
						symbol: "none",
						data: [],
						type: "line",
						lineStyle: {
							color: "#165DFF",
						},
						areaStyle: {
							color: new echarts.graphic.LinearGradient(
								0,
								0,
								0,
								1, // 渐变方向
								[{
										offset: 0,
										color: "rgba(22, 93, 255, 0.20)"
									}, // 渐变起始色
									{
										offset: 1,
										color: "rgba(22, 93, 255, 0)"
									}, // 渐变结束色，透明
								]
							),
						},
					}, ],
				},
			}
		},
		methods: {
			openPicker() {
				this.showPicker = true
			},
			closePicker() {
				this.showPicker = false
			},
			openPicker2() {
				this.showPicker2 = true
			},
			closePicker2() {
				this.showPicker2 = false
			},
			confirm(e) {
				const that = this
				that.showPicker = false
				that.currentFilterDate = e.value[0]
				const paramsLine = that.getParams(e.value[0])
				that.getLineData(paramsLine).then(() => {
					that.$refs.chartLine.setOption(that.optionLine)
				})
			},
			confirm2(e) {
				const that = this
				that.showPicker2 = false
				that.currentFilterDate2 = e.value[0]
				const paramsPie = that.getParams(e.value[0])
				that.getPieData(paramsPie).then(() => {
					that.$refs.chartPie.setOption(that.optionPie)
				})
			},
			getDate(n, type) {
				// 获取当前日期
				const currentDate = this.$moment();

				// 计算n个月前的日期
				const twelveMonthsAgo = this.$moment(currentDate).subtract(n, type);

				// 获取12个月的开始时间（即12个月前的今天的00:00:00）
				const startDate = twelveMonthsAgo
					.startOf("day")
					.format("YYYY-MM-DD HH:mm:ss");

				// 获取整整12个月的结束时间（即当前时间的23:59:59）
				const endDate = currentDate.endOf("day").format("YYYY-MM-DD HH:mm:ss");
				return {
					startDate,
					endDate
				}
			},
			getParams(currentFilterData) {
				return {
					resultType: currentFilterData.type === 'months' ? 'mouth' : 'day',
					analyzeBegin: this.getDate(currentFilterData.value, currentFilterData.type).startDate,
					analyzeEnd: this.getDate(currentFilterData.value, currentFilterData.type).endDate,
					id: this.$store.getters.userInfo.id
				}
			},
			// 获取折线图数据
			async getLineData(params) {
				const result = await getLineDataList(params);
				this.optionLine.series[0].data = result.data.map((item) => {
					return item.statisticalResult;
				});
				this.optionLine.xAxis.data = result.data.map((item) => {
					return item.statisticalItem;
				});

			},

			// 获取饼图数据
			async getPieData(params) {
				const result = await getPieDataList(params);
				const nameTypeToObjectMap = {}
				const pieDefaultData = [...this.defaultPieData]
				const total = result.data.reduce((sum, e) => sum + Number(e.statisticalResult || 0), 0)
				const resultData = result.data.map((item, index, arr) => {
					return {
						name: this.pieEnum[item.statisticalItem],
						value: item.statisticalResult,
						nameType: item.statisticalItem
					};
				});
				pieDefaultData.forEach(item => {
					nameTypeToObjectMap[item.nameType] = {
						...item
					};
				})
				resultData.forEach(item => {
					const existingItem = nameTypeToObjectMap[item.nameType];
					if (existingItem) {
						existingItem.value += Number(item.value);
					} else {
						nameTypeToObjectMap[item.nameType] = {
							...item
						};
					}
				});
				const mergedArray = Object.values(nameTypeToObjectMap);
				const lastResult = mergedArray.map(item => {
					const percent = item.value == 0 ? 0 : (item.value / total *
						100).toFixed(2);
					return {
						...item,
						name: item.name + ' ' + percent + '%',
					}
				})
				this.optionPie.series[0].data = lastResult
			},
		},
		mounted() {
			const that = this;
			const paramsLine = this.getParams(this.currentFilterDate)
			const paramsPie = this.getParams(this.currentFilterDate)
			this.getLineData(paramsLine).then(() => {
				that.$refs.chartLine.init(echarts, (chart) => {
					chart.setOption(that.optionLine);
				});
			})

			that.getPieData(paramsPie).then(() => {
				that.$refs.chartPie.init(echarts, (chart) => {
					chart.setOption(that.optionPie);
				});
			});

			// 用户总数
			getUserData({
				id: this.$store.getters.userInfo.id,
			}).then(result => {
				console.log(result)
				this.totalGrowCount = result.data
			})

			// 今日增长
			getUserData({
				id: this.$store.getters.userInfo.id,
				analyzeBegin: this.getDate(1, 'days').startDate,
				analyzeEnd: this.getDate(1, 'days').endDate
			}).then(result => {
				console.log(result)
				this.todayGrowCount = result.data
			})
		}
	}
</script>

<style>
	page {
		background: #F6F9FF !important;
		padding: 32rpx 28rpx;
		box-sizing: border-box;
	}
</style>

<style lang="scss" scoped>
	.dataArea {
		width: 100%;
		height: 238rpx;
		border-radius: 16rpx;
		background-color: #FFF;
		padding: 32rpx 28rpx;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		.data {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-around;

			.dataItem {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
			}
		}
	}

	.title {
		display: flex;
		align-items: center;

		&_line {
			width: 8rpx;
			height: 28rpx;
			border-radius: 200rpx;
			background-color: #588bf3;
			margin-right: 20rpx;
		}

		&_text {
			font-weight: bold;
			color: #333;
			font-size: 28rpx;
		}
	}

	.components {
		width: 100%;
		height: auto;
		background-color: #fff;
		border-radius: 20rpx;
		margin: 0 auto;
		margin-top: 24rpx;
		padding: 32rpx 28rpx;

		.head {
			display: flex;
			align-items: center;
			justify-content: space-between;
			align-items: center;
		}

		.line {
			width: 100%;
			height: 390rpx;
			margin-top: 20rpx;
		}

		.pie {
			width: 100%;
			height: 300rpx;
			margin-top: 20rpx;
		}

		.canvas {
			width: 100%;
			height: 100%;
		}
	}
</style>
